import 'dart:io';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

/// 应用错误类型
enum AppErrorType {
  network,
  file,
  permission,
  validation,
  ai,
  unknown
}

/// 应用错误模型
class AppError {
  final AppErrorType type;
  final String message;
  final String? details;
  final dynamic originalError;
  
  AppError({
    required this.type,
    required this.message,
    this.details,
    this.originalError,
  });
  
  @override
  String toString() => message;
}

/// 统一错误处理器
class ErrorHandler {
  // 常量定义
  static const String networkErrorMessage = '网络连接失败，请检查网络设置';
  static const String fileNotFoundMessage = '文件未找到或已被删除';
  static const String unknownErrorMessage = '发生未知错误，请重试';
  static const Duration messageDisplayDelay = Duration(seconds: 3);
  
  /// 处理通用错误
  static AppError handleError(dynamic error, {String? context}) {
    if (error is DioException) {
      return _handleDioError(error);
    }
    
    if (error is FileSystemException) {
      return _handleFileError(error);
    }
    
    if (error is ArgumentError) {
      return AppError(
        type: AppErrorType.validation,
        message: error.message ?? '参数错误',
        originalError: error,
      );
    }
    
    return AppError(
      type: AppErrorType.unknown,
      message: unknownErrorMessage,
      details: error.toString(),
      originalError: error,
    );
  }
  
  /// 处理网络错误
  static AppError _handleDioError(DioException error) {
    switch (error.type) {
      case DioExceptionType.connectionTimeout:
      case DioExceptionType.sendTimeout:
      case DioExceptionType.receiveTimeout:
        return AppError(
          type: AppErrorType.network,
          message: '网络请求超时，请检查网络连接',
          originalError: error,
        );
      case DioExceptionType.connectionError:
        return AppError(
          type: AppErrorType.network,
          message: networkErrorMessage,
          originalError: error,
        );
      case DioExceptionType.badResponse:
        return AppError(
          type: AppErrorType.network,
          message: '服务器响应错误：${error.response?.statusCode}',
          originalError: error,
        );
      default:
        return AppError(
          type: AppErrorType.network,
          message: '网络请求失败',
          originalError: error,
        );
    }
  }
  
  /// 处理文件错误
  static AppError _handleFileError(FileSystemException error) {
    return AppError(
      type: AppErrorType.file,
      message: fileNotFoundMessage,
      details: error.message,
      originalError: error,
    );
  }
  
  /// 显示错误消息
  static void showErrorSnackBar(BuildContext context, AppError error) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Row(
          children: [
            Icon(Icons.error_outline, color: Colors.white, size: 20),
            SizedBox(width: 8),
            Expanded(
              child: Text(
                error.message,
                style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
              ),
            ),
          ],
        ),
        backgroundColor: Colors.red[600],
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        duration: messageDisplayDelay,
      ),
    );
  }
  
  /// 显示成功消息
  static void showSuccessSnackBar(BuildContext context, String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Row(
          children: [
            Icon(Icons.check_circle_outline, color: Colors.white, size: 20),
            SizedBox(width: 8),
            Expanded(
              child: Text(
                message,
                style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
              ),
            ),
          ],
        ),
        backgroundColor: Colors.green[600],
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        duration: messageDisplayDelay,
      ),
    );
  }
} 